﻿/*
    dependent on:
        baseUrl
        user
*/

function getWeekStart(date)
{
    var day = date.getDay();
    var moveBy = (day - 1 + 7) % 7;
    var weekStart = new Date(date.getTime());
    weekStart.setDate(weekStart.getDate() - moveBy);

    return weekStart;
}

var Days = ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"];
var start = getWeekStart(new Date());
    
function getData(page, success)
{
    if(state.isSaving())
    {
        window.setTimeout(function(){getData(page, success)}, 1000);
        return;
    }
    closeEdit();
    if (page === 0)
    {
        state.Loading = true;
        $('.Contain').clarizen_table('showLoading');
    }
    else
        state.Paging = true;
    if(page != 0 && getData.isLoading)
        return;

    getData.isLoading = true;
        
    getData.count = getData.count + 1 || 0;
    var count = getData.count;
        
        remoteRequest({
        url: baseUrl + "/TimeSheet/List",
        contentType: "JSON",
        data: {start:start.stringify(), page:page||0, userID:$('#userFilter').val() || "", projectID:$('#projectFilter').val() || ""},
        type: "POST",
        success: function(data)
        { 
            if(count == getData.count) 
            {
                state.Loading = false;
                state.Paging = false;
                getData.isLoading = false;
                success(data);
            }
            else
                $('.Contain').clarizen_table('enablePaging', data.hasMore);
        }
    });
}

function getCell(timesheet)
{
    var val = timesheet;
    if(val)
    {
        var img = stringFormat("<span class='{0}'></span>",
            val.isApproved? 'Approved': 'NotApproved');
                            

        var imgHours = !val.RegularHours? stringFormat("<img src='{0}/Images/ico-overtime.gif'/>", baseUrl): "";
        var imgComment = val.Comment? stringFormat("<img src='{0}/Images/ico-note-small.gif'/>", baseUrl): "";

        return stringFormat("{0}<span class='Data'>{1}</span><span class='TS_Indicator'>{2}</span>" 
            ,val.isSubmited || val.isApproved? img: ""
            ,val.Duration.Value
            ,imgHours + imgComment);
    }
    return "<span class='Data'></span>";
}

function changeDate(backOrDate)
{
    if(backOrDate === true)
        start.setDate(start.getDate() - 7);
    else if(backOrDate === false)
        start.setDate(start.getDate() + 7);
    else
        start = getWeekStart($('#hfDate').datepicker( "getDate" ));

    getData(0, function(data)
    {
        $('.Contain').clarizen_table('drawHeader');
        $('.Contain').clarizen_table('reload', data.sheets);
        $('.Contain').clarizen_table('enablePaging', data.hasMore);
        $(".startText").html(start.stringify());
        $(".endText").html(start.addDays(7).stringify());
    });
}

function Duplicate()
{
    debugger;
    var element = $('.Contain').clarizen_table('getSelectedElement');
    var newElement = jQuery.extend(true, {}, element);
    newElement.TimeSheets = {};
    $('.Contain').clarizen_table('addElement', newElement, $('.Contain').clarizen_table('getSelectedRow'));
}

function LoadToolbar()
{
    var bar = $(".GridToolbar");

    var left = $("<div class='left'>");
    left.append(stringFormat("<span class='Duplicate span'>Duplicate line item</span>"));
    left.append("<span class='Seperator span'>");
    left.append(stringFormat("<span class='Approval span'>Submit for approval</span>"));
    left.append("<span class='Seperator span'>");
    left.append(stringFormat("<span class='Delete span'></span>"));
    left.append("<span class='Seperator span'>");
    bar.append(left);
    var end = new Date(start.getTime());
    end.setDate(start.getDate() + 7);
    
    //<select id='projectFilter'><option value=''>Select project</option></select>\
    var date = stringFormat("<div class='right'>\
                                <select id='userFilter'><option value='{2}'>{3}</option></select>\
                                <span><strong class='startText'>{0}</strong><em>to</em><strong class='endText'>{1}</strong></span>\
                                <span class='leftDate'></span><input type='hidden' id='hfDate'><span class='rightDate'></span>\
                                </div>"
                            , start.stringify()
                            , end.stringify()
                            , user? user.ID.Value: ""
                            , user? user.Name.substring (0,20): "");

    bar.append(date);
    bar.find('.leftDate').click(function()
    {
        changeDate(true);
    });

    bar.find('.rightDate').click(function()
    {
        changeDate(false);
    });

    bar.find('#hfDate').datepicker({
        onSelect: function()
        {
            changeDate("datepicker");
        },
        showOn:'button',
        buttonImageOnly:true,
        buttonImage:baseUrl + '/Images/16_icons.gif'
    });
    bar.find('#userFilter').searchForm({ 
        type: "User", 
        baseUrl: baseUrl, 
        filter: "userFilter",
        onselect:function()
        {
            getData(0, function(data)
            {
                $('.Contain').clarizen_table('enablePaging', data.hasMore);
                $('.Contain').clarizen_table('reload', data.sheets);
            });
        }
    });

    bar.find('#projectFilter').searchForm({ 
        type: "Project", 
        baseUrl: baseUrl, 
        filter: "projectFilter",
        addImg: true,
        onselect:function()
        {
            getData(0, function(data)
            {
                $('.Contain').clarizen_table('enablePaging', data.hasMore);
                $('.Contain').clarizen_table('reload', data.sheets);
            });
        }
    });
    
    bar.find('.Duplicate').click(Duplicate);
    bar.find('.Approval').click(submitEntries);
    bar.find('.Delete').click(deleteEntry);
}


function deleteEntry()
{
    var cell = $('.Contain').clarizen_table('getSelectedCell');
    var timeSheet = cell.data('timeSheet');
        
    if(state.isGettingData() || state.Submitting ||  cell.data('saving') || !timeSheet || !timeSheet.ID)
        return;
        
    remoteRequest({
        url: baseUrl + "/TimeSheet/Delete",
        contentType: "JSON",
        data: {"ID.Value":timeSheet.ID.Value},
        type: "POST",
        success: function(data)
        {
            state.Deleting--;
                
            $('.Contain').clarizen_table('indicateSaving', state.isSaving());
            if(!data.Data)
            {
                alert(data.ErrorMessage);
                cell.html(lastValue);
                cell.data('timeSheet', timeSheet);
                cell.closest('tr').data('entity').TimeSheets[cell.data('offset')] = timeSheet;
            }
        }
    });
    var lastValue = cell.html();
    state.Deleting++;
    $('.Contain').clarizen_table('indicateSaving', true);
    cell.html('');
    cell.removeData('timeSheet');
    cell.closest('tr').data('entity').TimeSheets[cell.data('offset')] = null;
}

function submitEntries()
{
    var sheets = $('.Contain td').map(function(idx,el){var ts = $(el).data('timeSheet'); return ts && !ts.isSubmited? ts.ID: null});

    if(state.isWorking() || !sheets.length)
    {
        window.setTimeout(submitEntries, 1000);
        return;
    }
        
    state.Submitting = true;
    $('.Contain').clarizen_table('indicateSaving', true);
    var data = $.map(sheets.toArray(), function (el, idx) { return encodeURIComponent(stringFormat("EntityId[{0}]", idx)) + "=" + el.Value }).join("&");
    
    debugger; 
    remoteRequest({
        url: baseUrl + "/TimeSheet/Submit",
        contentType: 'JSON',
        data: data,
        type: "POST",
        success: function(res)
        {
            $('.Contain').clarizen_table('indicateSaving', state.isSaving());
            state.Submitting = false;
            if(res.Data)
            {
                getData(0, function(data)
                {
                    $('.Contain').clarizen_table('reload', data.sheets);
                    $('.Contain').clarizen_table('enablePaging', data.hasMore);
                });
                alert("Submited");
            }
            else 
            {
                alert(res.ErrorMessage);
            }
        }
    });
}


function closeEdit()
{
    $('.Edit').hide();
    $('body').unbind('click', SaveEdit);
    state.Editing = false;
    $('.Edit input, .Edit textarea').blur();

    $('.REditor').remove();
}

var isSaved = false;
function SaveEdit()
{
    if(isSaved)
        return;
    isSaved = true;
    
    var el = $('.Edit');

    if(!el.find('.inputEdit input').val())
        deleteEntry();
    
    closeEdit();
        
    var val = +el.find('.inputEdit input').val();
    var editType = $('.Edit').data('editType');
    var td = $('.Edit').data('td');
    var tr = td.closest('tr');
    var workItem = tr.data('entity');

    if(editType == editTypes.percent)
    {
        SavePercent(val, workItem, td);
        return
    }

    var timeSheet = td.data('timeSheet');
    var dayOffset = +td.data('offset');
    if(!val || val === 0)
        return;
    if(!(val > 0 && val <= 24))
    {
        alert("The value should be less than 24 hours");
        return;
    }
        
    var data = {
        //Duration: {Value:el.find('.inputEdit input').val(), Unit:"Hours"},
        "Duration.Value":el.find('.inputEdit input').val(), 
        "Duration.Unit":"Hours", 
        Comment: el.find('textarea').val(), 
        RegularHours: !el.find('#cb_overtime').attr('checked'), 
        "ID.Value": timeSheet? timeSheet.ID.Value: ""
    };
    if(!timeSheet)
    {
        var date = new Date(start.getTime());
        date.setDate(date.getDate() + dayOffset);
        data.ReportedDate = date.stringify();
        data.WorkItemID = workItem.ID.Value;
    }
    var updatedTimesheet = $.extend({}, timeSheet, data);
    updatedTimesheet = $.extend({}, updatedTimesheet, { Duration: { Value: el.find('.inputEdit input').val(), Unit: "Hours"} });
    if(timeSheet && timeSheet.Duration.Value == data["Duration.Value"] && (timeSheet.Comment? timeSheet.Comment: "") == data.Comment && timeSheet.RegularHours == data.RegularHours)
        return;
    state.Creating++;
    $('.Contain').clarizen_table('indicateSaving', true);
    remoteRequest({
        url: baseUrl + "/TimeSheet/edit",
        contentType: "JSON",
        type: "POST",
        data:data,
        success: function (res)
        {
            state.Creating--;
            $('.Contain').clarizen_table('indicateSaving', state.isSaving());
            if(res.Data)
            {
                updatedTimesheet.ID = res.Data;
                td.data('timeSheet', updatedTimesheet);
                workItem.TimeSheets[dayOffset] = updatedTimesheet;
            }
            else 
            {
                td.html(lastValue);
                alert(res.ErrorMessage);
            }

            td.data('saving', false);
        }
    });
    var lastValue = td.html();
    td.html(getCell(updatedTimesheet));
    td.data('saving', true);
}

function SavePercent(val, workItem, td)
{
    var col = $('.Contain').clarizen_table('getCol', td);
    if(!isNumber(val) || val < 0 || val > 100)
    {
        alert("value should be between 0 and 100");
        return;   
    }

    if(workItem.PercentCompleted == val)
        return;

    state.Updating++;
    $('.Contain').clarizen_table('indicateSaving', true);
    remoteRequest({
        url: baseUrl + "/WorkItem/edit",
        contentType: "JSON",
        type: "POST",
        data:{"ID.Value": workItem.ID.Value, PercentCompleted: val},
        success: function (res)
        {
            state.Updating--;
            $('.Contain').clarizen_table('indicateSaving', state.isSaving());
            if(!res.Data)
            {
                workItem.P_Completed = lastValue;
                td.html(col.getData(workItem));
                alert(res.ErrorMessage);
            }
        }
    });

    var lastValue = workItem.PercentCompleted;
    workItem.PercentCompleted = val;
    td.html(col.getData(workItem));
}


var editTypes = {
    timeSheet: 0,
    percent: 1 
};

function openEdit(el, clearValue)
{
    if(state.Loading || el.data('saving'))
        return;

    state.Editing = true;
    isSaved = false;
    var col = $('.Contain').clarizen_table('getCol', el);
    editType = col.getName() == "% Completed"? editTypes.percent: editTypes.timeSheet;

    var task = $('.Contain').clarizen_table('getSelectedElement');
    
    if(task.IndividualReporting && editType == editTypes.percent)
    {
        openResourceEdit(task, "PercentCompleted", el, function(savedTask)
        {
            task.PercentCompleted = savedTask.PercentCompleted;
            task.Resources = savedTask.Resources;
            $(el).html(col.getData(task));
        });
        return;
    }

    var editor = $('.Edit');
    if(!editor.length)
    {
        editor =  "<div class='Edit'>\
                        <div class='inputEdit'>\
                            <input type='text'/>\
                        </div>\
                        <div class='comment-box'>\
                            <div class='overtime'><input type='checkbox' id='cb_overtime'/><label for='cb_overtime'>overtime</label><a class='close' onclick='closeEdit()'></a></div>\
                            <div>Comment</div>\
                            <textarea id='tbComment'></textarea>\
                            <span class='arrow'></span>\
                        </div>\
                    </div>";
        $('body').append(editor);
        editor = $('.Edit');
            
        editor.keydown(function(e)
        {
            e.stopPropagation();
        }).find('input').keydown(function(e)
        {
            if (e.keyCode == 13)
            {
                SaveEdit();
                closeEdit();
            }
            else if (e.keyCode == 27)//esc
                closeEdit();
        });

        editor.click(function(e)
        {
            e.stopPropagation();
        });
    }
        
        
    var val;

    if(editType == editTypes.timeSheet)
    {
        editor.find('.comment-box').show();
        val = el.find('.Data').html();
        var timeSheet = el.data('timeSheet') || {RegularHours:true};
        editor.find('textarea').val(timeSheet.Comment);
        editor.find('[type=checkbox]').attr('checked', timeSheet.RegularHours === true? false: true);
    }
    else if(editType == editTypes.percent)
    {
        editor.find('.comment-box').hide();
        val = el.closest('tr').data('entity').PercentCompleted;
    }
        
    //display
    var offset = el.offset();
    editor.css({left:offset.left,top:offset.top});
    editor.show();
    //save data for future use
    editor.data('td', el);
    editor.data('editType', editType);
        
    var input = editor.find('.inputEdit input');
    input.val(clearValue || !val? "": Math.round(val));
    input.focus();
        
    $('body').bind('click', function(){SaveEdit(); closeEdit();});
}

var state = {
    Creating:0,
    Editing:false,
    Paging:false,
    Loading:false,
    Deleting:0,
    Updating:0,
    Submitting: false,

    isGettingData: function()
    {
        return this.Paging || this.Loading;
    },

    isWorking: function()
    {
        return this.isGettingData() || this.isSaving() || this.Submitting;
    },

    isSaving: function()
    {
        return this.Creating ||this.Updating || this.Deleting;
    }
}


var initPage = function () {
    var cols = [];

    cols.push(new Column({
        name: "SYSID",
        displayName: "ID"
    }));
    cols.push(new Column({
        name: "Name",
        displayName: "Work item"
    }));

    cols.push(new Column({
        displayName: "Actual Effort",
        getData: function (item) {
            return item.ActualEffort ? round(item.ActualEffort.Value, 2) + " " + durationUnits[item.ActualEffort.Unit] : "";
        }
    }));
    cols.push(new Column({
        displayName: "Remaining Effort",
        getData: function (item) {
            return item.RemainingEffort ? round(item.RemainingEffort.Value, 2) + " " + durationUnits[item.RemainingEffort.Unit] : "";
        }
    }));
    cols.push(new Column({
        displayName: "% Complete",
        getData: function (item) {
            return item.PercentCompleted ? Math.round(item.PercentCompleted) + "%" : "";
        },
        getHiddenData: function (item) {
            return [{ name: "editable", val: true}];
        }
    }));



    var tip = "<div><b><%= this.Name %></b></div>\
        <div><%= this.Parent_Name %></div>\
        <div><%= this.ParentProject_Name %></div>\
        <div>Due: <%= this.DueDateString %></div>\
        <div><%= this.PercentCompleted %>%</div>";
    var curDate = new Date(start.getTime());
    for (var i = 0; i < 7; i++) {
        cols.push(new Column({
            getData: (function (i) {
                return function (item) { return getCell(item.TimeSheets[i.toString()]) }
            })(i),
            getName: (function (i) {
                return function () {
                    var date = start.addDays(i);
                    return date.getDate() + " " + Days[date.getDay()]
                }
            })(i),
            getHiddenData: (function (i) {
                return function (item) {
                    var data = [{ name: "offset", val: i}];

                    var val = item.TimeSheets[i.toString()];
                    if (val)
                        data.push({ name: "timeSheet", val: val });
                    data.push({ name: "editable", val: !val || !val.isApproved });
                    return data;
                }
            })(i),
            className: "TS" + (i > 4 ? " non-working" : "")
        }));
    }
    LoadToolbar();

    $('.Contain').clarizen_table({
        cols: cols,
        headerstyle: 'HeaderTS',
        elements: [],
        beforeCellClick: function () {
            if (state.Editing)
                SaveEdit();
            if ($(this).hasClass('Selected')) // only edit on second click
            {
                if ($(this).data('editable'))
                    openEdit($(this));
            }
        },
        page: function (page, callback) {
            getData(page, function (data) {
                callback(data.sheets);
                $('.Contain').clarizen_table('enablePaging', data.hasMore);
            });
        },
        height: $.browser.msie ? 345 : 390,
        baseUrl: baseUrl,
        afterCreated: function (trs) {
            trs.each(function () {
                var element = $(this).data('entity');
                $(this).find('td').tipTip({ content: $.jqote(tip, element) });
            });
        },
        padding: 4
    });
    $(document).keydown(function (e) {
        var cell = $('.Contain').clarizen_table('getSelectedCell');

        if ($(".sf_nameFilter").length== 0) {
            if (e.keyCode == 46 || e.keyCode == 8)// del
            {
                deleteEntry();
                e.preventDefault();
            }
            else if (e.keyCode == 27)//esc
                closeEdit();
            // enter + digits
            else if (!state.Editing && cell.length && cell.data('editable')) {
                if (e.keyCode == 13)
                    openEdit(cell);
                else if ((e.keyCode >= "0".charCodeAt(0) && e.keyCode <= "9".charCodeAt(0))) {
                    openEdit(cell, true);
                }
            }
        }
    });
    getData(0, function (data) {
        $('.Contain').clarizen_table('reload', data.sheets);
        $('.Contain').clarizen_table('enablePaging', data.hasMore);
    });
};



function AttachEvents(container)
{
    $('.Numeric', container).blur(function (event)
    {
        if (!/^(\d+(\.\d+)?)?$/.test($(this).val()))
            $(this).val(0);
    });
}

initPage();
